package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.login.LoginException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private VMService vmService;
    @Autowired
    private TaskDetailsService taskDetailsService;
    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    /**
     * 新增工单 ---运维和运营工单是同一个接口
     *
     * @param model
     */
    @Override
    public boolean createTask(TaskViewModel model) {
        //对是否存在同类型工单进行判断
        if (ifExistDuplicateTask(model.getInnerCode(), model.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        //1.先判断设备的状态,根据售货机编号查询售货机
        //通过feign,调用VMService 查询售货机相关信息
        VmVO vmInfo = vmService.getVMInfo(model.getInnerCode());
        //1.2参数的检查  (工单类型与售货机的状态的关系)
        check(vmInfo, model.getProductType());

        //新增工单记录表
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(model, taskEntity);
        //参数补齐
        taskEntity.setCreateType(model.getCreateType());
        //生成taskCode
        taskEntity.setTaskCode(generateTaskCode());
        //工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        taskEntity.setProductTypeId(model.getProductType());
        taskEntity.setDesc(model.getDesc());
        taskEntity.setInnerCode(model.getInnerCode());
        taskEntity.setUserId(model.getUserId());
        //获取
        UserVO user = getUserVO(model);
        taskEntity.setUserName(user.getUserName());
        save(taskEntity);
        //如果taksType为supply  就可以进行补货
        if (!taskEntity.getTaskType().equals(VMSystem.TASK_TYPE_SUPPLY)) {
            throw new LogicException("当前工单状态异常");
        }
        //补货
        addGoodsTask(model, taskEntity);
        //自动创建工单到,存入ZSET
        // TODO
        return true;
    }

    /**
     * 接受工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean acceptTask(Long id) {
        TaskEntity taskEntity = this.getById(id);
        //判断工单状态是否是待处理状态
        if (!taskEntity.getTaskStatus().equals(VMSystem.TASK_STATUS_CREATE)) {
            throw new LogicException("工单状态不是待处理");
        }
        //修改工单状态为进行
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        return this.updateById(taskEntity);

    }

    /**
     * 取消工单
     *
     * @param id
     * @param cancelVM
     * @return
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        //根据id查询对应工单
        TaskEntity taskEntity = getById(id);
        //判断工单的状态  如果是完成或取消状态,怎抛出异常
        if (taskEntity.getTaskStatus().equals(VMSystem.TASK_STATUS_FINISH)) {
            throw new LogicException("工单已经完成");
        }
        if (taskEntity.getTaskStatus().equals(VMSystem.TASK_STATUS_CANCEL)) {
            throw new LogicException("工单已经取消");
        }
        //工单状态是待处理,则可以进行取消操作
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        //自动取消工单,从ZSET中减1
        // TODO
        return this.updateById(taskEntity);
    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(long id) {
        //获取当前工单
        TaskEntity taskEntity = this.getById(id);
        //判断当前工单的状态  如果是完成或取消,则抛出异常
        if (taskEntity.getTaskStatus().equals(VMSystem.TASK_STATUS_FINISH)) {
            throw new LogicException("当前工单状态已经完成");
        }
        if (taskEntity.getTaskStatus().equals(VMSystem.TASK_STATUS_CANCEL)) {
            throw new LogicException("当前工单状态已经取消");
        }
        this.updateById(taskEntity);

        //如果是投放工单或撤机工单,就要进行运维
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY
                || taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {
            //运维工单封装与下发,更改工单的状态
            modifyVMServiceStatus(taskEntity);
        }
        //如果是补货工单,进行补货
        if (taskEntity.getProductTypeId().equals(VMSystem.TASK_TYPE_SUPPLY)) {
            modefyVMServiceSupply(taskEntity);
        }
        return true;
    }

    /**
     * 更新工单量列表
     *
     * @param taskEntity
     * @param score      增加的分值
     */
    @Override
    public void updateTaskZSet(TaskViewModel model, int score, String userRepairer) {
      // TODO
    }

    /**
     * @param taskEntity
     */
    private void modefyVMServiceSupply(TaskEntity taskEntity) {
        //查询
        LambdaQueryWrapper<TaskDetailsEntity> wrapper = new LambdaQueryWrapper();
        wrapper.eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId());
        //补货任务详情
        List<TaskDetailsEntity> detailsEntities = taskDetailsService.list(wrapper);
        //补货协议
        SupplyContract supplyContract = new SupplyContract();
        //售货机编号
        supplyContract.setInnerCode(taskEntity.getInnerCode());
        //补货数据明细
        List<SupplyChannel> supplyChannels = Lists.newArrayList();
        //从工单明细表提取数据加到补货数据中
        for (TaskDetailsEntity detailsEntity : detailsEntities) {
            SupplyChannel channel = new SupplyChannel();
            //设置货道编号
            channel.setChannelId(detailsEntity.getChannelCode());
            //补货数量
            channel.setCapacity(detailsEntity.getExpectCapacity());
            //商品编号
            channel.setSkuId(detailsEntity.getSkuId());
            //保存
            supplyChannels.add(channel);
        }
        try {
            //当使用异常捕获时,要考虑异常的处理会不会影响之前的代码逻辑
            mqttProducer.send(TopicConfig.TASK_SUPPLY_TOPIC, 1, supplyChannels);
        } catch (JsonProcessingException e) {
            log.error("消息发送异常", e);
            throw new LogicException("补货工单消息发送异常");
        }
    }


    /**
     * 运维工单封装与下发
     *
     * @param taskEntity
     */
    private void modifyVMServiceStatus(TaskEntity taskEntity) {
        //向机器微服务发送消息,通知更改售货机的状态
        //封装消息
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());
        //向EMQ发送消息
        try {
            //当使用异常捕获时,要考虑异常的处理会不会影响之前的代码逻辑
            mqttProducer.send(TopicConfig.TASK_SUPPLY_TOPIC, 1, taskCompleteContract);
        } catch (JsonProcessingException e) {
            log.error("消息发送异常", e);
        }
    }

    /**
     * 补货类型的工单
     *
     * @param model
     * @param taskEntity
     */
    private void addGoodsTask(TaskViewModel model, TaskEntity taskEntity) {
        //如果是补货工单，向 工单明细表插入记录
        if (taskEntity.getProductTypeId().equals(VMSystem.TASK_TYPE_SUPPLY)) {
            // List<TaskDetailsViewModel> details = model.getDetails();
            //lambda中  (参数列表)->goes to{方法体}
            model.getDetails().forEach(details -> {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(details, detailsEntity);
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
    }

    /**
     * 获取 user
     *
     * @param model
     * @return
     */
    private UserVO getUserVO(TaskViewModel model) {
        //调用feign,调用userService获取user
        UserVO user = userService.getUser(model.getUserId());
        if (user == null) {
            //逻辑异常,没有执行人信息
            throw new LogicException("执行人不存在");
        }
        return user;
    }

    /**
     * 检查参数    校验售货机
     *
     * @param vmInfo      售货机设备
     * @param productType 工单类型
     */
    private void check(VmVO vmInfo, int productType) {

        //根据设备编号查询设备,并对vmInfo进行健壮性判断
        if (vmInfo == null) {
            throw new LogicException("设备校验失败");
        }
        //根据不同的工单类型校验
        //如果是投放工单，状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus().equals(VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && !vmInfo.getVmStatus().equals(VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && !vmInfo.getVmStatus().equals(VMSystem.VM_STATUS_RUNNING)) {
            throw new LogicException("该设备不在运营状态");
        }

    }

    /**
     * 生成 taskCode
     */
    public String generateTaskCode() {
        //code的组成是yyMMdd+编号格式
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        //redis的key
        String key = "lkd+task.code" + date;
        //用redis实现
        Object obj = redisTemplate.opsForValue().get(key);
        //进行非空判断
        if (obj == null) {
            //表明当前时间内暂无taskCode生成
            redisTemplate.opsForValue().set(key, 0, Duration.ofDays(1));
        }
        //key开始为零,如果不为空便自增1,(如何保证线程安全)
        return date + String.format(redisTemplate.opsForValue().increment(key, 1).toString());
    }

    /**
     * 校验同一台设备是否有未完成同类型工单
     *
     * @param innerCode      售货机编码
     * @param productionType 工单类型
     * @return
     */
    private boolean ifExistDuplicateTask(String innerCode, int productionType) {
        QueryWrapper<TaskEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productionType)
                //正在进行
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(queryWrapper) > 0;
    }

}

